var app = getApp(),
  a = app.requirejs("core");
var running = false;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    show:false,
    meal: [],
    meal_index:-1,
    user:{'money':0.00}
  },
  onLoad: function (e) {
    var that = this;
    a.setting();
    that.setData({
      userinfo: getApp().getCache("userinfo")
    });
    that.getinfo();
  },
  getinfo: function () {
    var that = this;
    var meal_index=-1;
    a.get('Usercard/rechargemeal', {
      uid: app.getCache('userinfo').uid
    }, function (t) {
      if (t.code == 0){
        if(t.info.meal.length>0){
          meal_index=0;
        }
        that.setData({
          user: t.info.user,
          meal: t.info.meal,
          meal_index: meal_index,
          show: true
        })
      }else{
        a.alert(t.msg);
      }
    }, !that.data.show);
  },
  select_meal:function(e){
    var that=this,
    i=a.pdata(e).index;
    that.setData({meal_index:i})
  },
  chongzhi:function(){
    var that = this;
    var data={};
    var i = that.data.meal_index;
    if (running){
      return;
    }
    if (i==-1) {
      a.alert('未选择充值套餐');
      return;
    }
    data.payprice = that.data.meal[i]['money'];
    data.giveprice = that.data.meal[i]['reward'];
    data.card_id=that.data.user.id;
    data.integral = that.data.meal[i]['integral'];
    data.openid = app.getCache('userinfo').openid;
    running = true;
    a.post('Usercard/createOrder', data, function (t) {
      running = false;
      if (t.code == 0) {
        wx.requestPayment({
          'timeStamp': t.info.timeStamp,
          'nonceStr': t.info.nonceStr,
          'package': t.info.package,
          'signType': 'MD5',
          'paySign': t.info.paySign,
          'success': function (res) {
            if (res.errMsg == "requestPayment:ok") {
              a.success('充值成功');
              setTimeout(function () {
                a.jump('', 5);
              });

            } else {
              a.error('支付失败！');
            }
          },
          'fail': function (res) {
            a.error('您已经取消支付！')
          }
        })
      } else {
        a.alert(t.msg);
      }
    })
  }
})